<template>
  <div class="purchase-products-list-component-page">
    <div class="block">
      <header>
        <h2 class="required">3、销售产品</h2>
      </header>
      <section style="height:400px;">
        <el-row class="block-item">
          <el-button
            type="primary"
            :disabled="!disabledAddSaleBtn"
            @click="onOpenImportProduct"
            >模板导入产品</el-button
          >
          <el-divider direction="vertical" />
          <el-button type="text" @click="onGetProductTemplate"
            >模板下载</el-button
          >
          <div class="InvoiceNumberSty">
            <el-button
              :disabled="!disabledAddSaleBtn"
              type="primary"
              @click="dialogCopyInvoiceNumberEvent"
            >
              批量录入发票号
            </el-button>
            <el-button
              :disabled="!disabledAddSaleBtn"
              type="primary"
              @click="onOpenProductDialog"
              >添加销售产品</el-button
            >
          </div>
        </el-row>
        <el-editable
          :columns="SELECTED_PRODUCTS_COLUMNS"
          :payload="payload_products"
          :need-pagination="true"
          height="200"
          :row-key="row => row.mixsIds"
          @reload="reloadData"
          @selection-change="handleSelectionChange"
        >
          <template #default-stockCount="{ row, $index }">
            <div>
              <el-input-number
                v-model="row.referencePrice"
                :step="1"
                :precision="2"
                size="small"
                :min="0.0"
                :max="99999999.99"
                @change="onChangeReferencePrice(row, $index)"
              />
            </div>
          </template>
          <template #default-productCount="{ row, $index }">
            <div v-if="!row.seqNo">
              <el-input-number
                v-model="row.productCount"
                :step="1"
                step-strictly
                size="small"
                :min="1"
                :max="row.availableCount"
                @change="onChangeCount(row, $index)"
              />
              <span style="margin-left:10px;color:red;"
                >可用量{{ row.availableCount }}</span
              >
            </div>
            <div v-else style="width: 130px;text-align: center;">
              {{ row.productCount }}
            </div>
          </template>
          <template slot="default-invoiceNum" slot-scope="scope">
            <el-input
              v-model="scope.row.invoiceNum"
              maxlength="30"
              onkeyup="this.value=this.value.replace(/\D/g,'')"
              onafterpaste="this.value=this.value.replace(/\D/g,'')"
            />
          </template>
          <template #default-opt="{ row, $index }">
            <a
              href="javascript:;"
              style="text-decoration: none"
              @click="onDeleteProduct(row, $index)"
              >删除</a
            >
          </template>
          <!-- 给创建报台用的表格内表单 -->
        </el-editable>
      </section>
    </div>
    <upload
      ref="upload"
      :params="stepOneFormData"
      @complete="getUploadProducts"
    />
    <!-- 复制发票号弹窗 -->
    <el-dialog
      :visible.sync="dialogTableVisible"
      :close-on-click-modal="false"
      title="批量录入发票号"
      width="400px"
      :modal="false"
      class="dialogSty"
    >
      <!-- <el-input
        v-model="inputCopyInvoiceNum"
        maxlength="30"
        placeholder=""
        onkeyup="this.value=this.value.replace(/\D/g,'')"
        onafterpaste="this.value=this.value.replace(/\D/g,'')"
      ></el-input> -->
      <el-input
        v-model="inputCopyInvoiceNum"
        maxlength="30"
        @input="
          value => {
            inputCopyInvoiceNum = value.replace(/\D/g, '');
          }
        "
      ></el-input>
      <span class="spaSty" @click="empty">X</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="determineCopyColse">取 消</el-button>
        <el-button type="primary" @click="determineCopy">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import ElEditable from '@components/el-editable';
import { urlDownload } from '@const/utils';
import upload from '@/components/report-bills-management/distributor/upload';
import { computeRate, formatPrice } from '@const/filter';
import { IndexService } from './purchase-products-list.service';
import * as CONSTS from './purchase-products-list.const';
import { ProductAddDialogService } from '~/modules/sale-product/product-add.dialog.module';

const service = new IndexService();

export default {
  components: {
    ElEditable,
    upload
  },
  props: {
    stepOneFormData: {
      type: Object
    },
    products: {
      type: Array
    },
    type: {
      type: String,
      default: 'default'
    },
    operationType: String,
    title: String
  },
  data() {
    return {
      ...CONSTS,
      invoiceNum: '', // 发票号
      changeArrList: [], // 勾选的数据
      changeValue: [],
      idList: [],
      dialogTableVisible: false,
      inputCopyInvoiceNum: '',
      _products: [],
      payload_products: {},
      pager: {
        number: 1,
        size: 20
      },
      // 由于更新数量的动态性，下标的切换要同步。故这样搞
      index: {
        start: 1,
        end: 1
      }
    };
  },
  computed: {
    productAddDialogService() {
      return new ProductAddDialogService(this.$axios, this.$store, {
        type: this.type
      });
    },
    disabledAddSaleBtn() {
      return (
        this.stepOneFormData.create.contract &&
        this.stepOneFormData.create.supplier &&
        this.stepOneFormData.sales_info.date &&
        this.stepOneFormData.sales_info.target
      );
    }
  },
  watch: {
    products: {
      handler(val, oldVal) {
        if (val !== undefined) {
          this._products = val;
          const startIndex = (this.pager.number - 1) * this.pager.size;
          const endIndex = this.pager.number * this.pager.size;
          this.payload_products = service.getPayload(
            this._products,
            this.pager,
            startIndex,
            endIndex
          );
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // 关闭弹框
    determineCopyColse() {
      this.dialogTableVisible = false;
      this.inputCopyInvoiceNum = '';
    },
    // 弹框确认事件
    determineCopy() {
      console.log(this.inputCopyInvoiceNum);
      const num = this.inputCopyInvoiceNum;
      if (!this.inputCopyInvoiceNum) {
        // debugger
        this.$message({
          message: '请输入发票号',
          type: 'warning'
        });
        this.dialogTableVisible = true;
      } else if (num) {
        this.idList = this.changeArrList.map(item => item.mixsIds);
        this.products.map(i => {
          if (this.idList.includes(i.mixsIds)) {
            this.$set(i, 'invoiceNum', num);
          }
        });

        // this.payload_products.content.map(i => {
        //   if (this.idList.includes(i.mixsIds)) {
        //     this.$set(i, 'invoiceNum', num);
        //   }
        // });
        this.dialogTableVisible = false;
      }
    },
    empty() {
      this.inputCopyInvoiceNum = '';
    },
    // 弹窗打开事件
    dialogCopyInvoiceNumberEvent() {
      this.inputCopyInvoiceNum = '';
      if (this.changeArrList.length === 0) {
        this.$message({
          message: '请勾选数据'
        });
        this.dialogTableVisible = false;
      } else {
        this.dialogTableVisible = true;
      }
    },
    // 勾选数据
    handleSelectionChange(val) {
      this.changeArrList = val;
    },
    getUploadProducts(payload) {
      const data = this.products.concat(payload);
      const obj = {};
      const result = data.reduce((prev, cur, index, array) => {
        if (obj[cur.mixsIds]) {
          const foundIndex = prev.findIndex(
            item => item.mixsIds === cur.mixsIds
          );
          prev[foundIndex].invoiceNum = cur.invoiceNum;
          prev[foundIndex].productCount += Number(cur.productCount);
        } else {
          obj[cur.mixsIds] = true && prev.push(cur);
        }
        return prev;
      }, []);
      this.$emit('update:products', result);
      // const loadProductList = payload;
      // if (loadProductList.length > 0) {
      //   this.updateProductData(payload, true);
      // }
    },
    // 前端分页逻辑
    reloadData(pager) {
      const startIndex = (pager.number - 1) * pager.size;
      const endIndex = pager.number * pager.size;
      this.payload_products = service.getPayload(
        this._products,
        pager,
        startIndex,
        endIndex
      );
      this.pager = pager;
    },
    onDeleteProduct(row, index) {
      const startIndex = (this.pager.number - 1) * this.pager.size;
      const endIndex = this.pager.number * this.pager.size;
      this._products.splice(startIndex + index, 1);
      this.payload_products = service.getPayload(
        this._products,
        this.pager,
        startIndex,
        endIndex
      );
      if (this.payload_products.content.length === 0) {
        // 如果当前获取的内容为空，那么要重新获取一下数据
        this.pager.number = this.pager.number - 1;
        if (this.pager.number <= 0) this.pager.number = 1;
        const startIndex = (this.pager.number - 1) * this.pager.size;
        const endIndex = this.pager.number * this.pager.size;
        this.payload_products = service.getPayload(
          this._products,
          this.pager,
          startIndex,
          endIndex
        );
      }
      this.$emit('update:products', this._products);
    },
    onChangeCount(row, idx) {
      if (row.productCount >= row.availableCount) {
        row.productCount = row.availableCount;
      }
      if (!row.productCount) {
        this.$nextTick(() => {
          row.productCount = 1;
        });
      }
      this.calcCurTotalFee(row, idx);
      this.$emit('update:products', this._products);
    },
    onChangeReferencePrice(row, idx) {
      this.calcCurTotalFee(row, idx);
    },
    calcCurTotalFee(row, idx) {
      row.totalFee = formatPrice(
        computeRate(row.referencePrice, row.productCount),
        2
      );
    },
    onOpenProductDialog() {
      // 这里的formData传递完整的数据，再在子组件内整理成子级组件想要的数据格式，
      // 实际上这样做是“不好的”，但是由于数据的复杂度和混乱度，故此选择。
      // 再有一个原因是，产品搜索列表还需要一些额外的参数
      this.productAddDialogService
        .create({
          title: '添加销售产品',
          query: {
            operationType: this.operationType,
            formData: this.stepOneFormData
          },
          confirmButtonClickHandler: (data = {}) => {
            data.forEach(element => {
              this.$set(element, 'productCount', 1);
              this.$set(
                element,
                'totalFee',
                formatPrice(
                  computeRate(element.referencePrice, element.productCount),
                  2
                )
              );
            });
            this.updateProductData(data);
          }
        })
        .mount();
    },
    updateProductData(data, isImport) {
      this._products = service.reConcatSelectData(
        data,
        this._products,
        'mixsIds',
        isImport
      );
      const startIndex = (this.pager.number - 1) * this.pager.size;
      const endIndex = this.pager.number * this.pager.size;
      this.payload_products = service.getPayload(
        this._products,
        this.pager,
        startIndex,
        endIndex
      );
      this.$emit('update:products', this._products);
    },
    onOpenImportProduct() {
      this.$refs.upload.dialog_visible = true;
    },
    onGetProductTemplate() {
      urlDownload(
        'https://mt.heng-tai.com.cn/guoke-channel-aggregation-center/api/v1/files/download/41xolo3zi9b77c35ytw6yoda5xphw9m0.xlsx'
      );
    }
  }
};
</script>
<style lang="less" scoped>
.InvoiceNumberSty {
  float: right;
}

.spaSty {
  cursor: pointer;
  position: absolute;
  left: 362px;
  top: 97px;
  font-size: 18px;
}
.el-editable {
  height: 400px;
}
</style>
